﻿using StandXunYouServer.Dto;
using StandXunYouServer.IRepository;
using StandXunYouServer.IServices;
using StandXunYouServer.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StandXunYouServer.Services
{
    public class LotteryServices : ILotteryServices
    {
        private readonly IBaseRepository _baseConn;

        public LotteryServices(IBaseRepository baseConn)
        {
            _baseConn = baseConn;
        }

        public async Task<IEnumerable<Prizes>> GetPrizesQueryAsync()
        {
            var pList = await _baseConn.QueryAllAsync<Prizes>("select * from Prizes");
            return pList;
        }

        public async Task<IEnumerable<Prizes>> GetPrizesIsZeroQueryAsync()
        {
            var sql = "select * from Prizes where PrizeCount > 0";
            var pList = await _baseConn.QueryAllAsync<Prizes>(sql);
            return pList;
        }

        public async Task<IEnumerable<UserPrizeDto>> GetByUserIdQueryAsync(string userId)
        {
            string uPrizeSql = "select u.UserName as UserName, p.PrizeName as PrizeName, p.PrizeImagePath as PrizeImagePath, Count(up.PrizeId) as PrizeCount from ";

            uPrizeSql += "Users u inner join UserPrize up on u.Id = up.UserId inner join Prizes p on p.PrizeId = up.PrizeId ";

            uPrizeSql += "where u.Id = @userId group by u.UserName,up.PrizeId,p.PrizeName,p.PrizeImagePath ";

            //查询用户所有奖品
            var pList = await _baseConn.QueryAsync<UserPrizeDto>(uPrizeSql, new { userId = userId });

            return pList;
        }
        
        public async Task<int> IsUserPointsAsync(string userId)
        {
            var sql = "select UserPoints from Users where Id =@Id ";
            var result = await _baseConn.QueryFirstOrDefaultAsync<string>(sql, new { Id = userId });
            return Convert.ToInt32(result);
        }

        public async Task<bool> UpdatePointsPrizeCountAndInsertUserPrizeAsync(string userId, UserPrize model)
        {
            var sql1 = "update Users set UserPoints -= 25 where Id =@Id";
            var sql2 = "update Prizes set PrizeCount -= 1 where PrizeId =@prizeId";
            var result = await _baseConn.UpdateTwoAndInsertTranAsync(sql1, sql2, new { Id = userId, prizeId = model.PrizeId }, model);
            return result;
        }
    }
}
